package com.yaopaikeji.controller;

import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.constants.RestResult;
import com.yaopaikeji.constants.ResultsEnum;
import com.yaopaikeji.interceptor.Auth;
import com.yaopaikeji.model.RoleInfo;
import com.yaopaikeji.model.User;
import com.yaopaikeji.service.UserService;
import com.yaopaikeji.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Auth(Constants.ROLE_ROOT_NAME)
    @GetMapping("/list/all")
    public RestResult<List<User>> listAllUsers(){

        return new RestResult<>(userService.getAllUsers());
    }

    @Auth(Constants.ROLE_ROOT_NAME)
    @PostMapping(value = "/add")
    public RestResult<User> addNew(@RequestBody User user){

        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setId(Constants.ROLE_ADMIN_NUM);
        user.setIsActive(Constants.INACTIVE);
        user.setCreateTime(TimeUtil.now());
        user.setRoleInfo(roleInfo);

        return new RestResult<>(userService.addNew(user));
    }

    @Auth(Constants.ROLE_ROOT_NAME)
    @GetMapping("/delete/{id}")
    public RestResult deleteUser(@PathVariable("id")Integer id){

        User user = new User();
        user.setId(id);

        userService.deleteUser(user);

        return new RestResult();
    }

    @Auth
    @PostMapping("/update")
    public RestResult<User> updateUser(@RequestBody User user){

        return new RestResult<>(userService.updateUserInfo(user));
    }

    @Auth(Constants.ROLE_ROOT_NAME)
    @GetMapping("/active/{id}")
    public RestResult activeUser(@PathVariable("id")Integer id){

        User user = new User();
        user.setId(id);

        return new RestResult(userService.activeUser(user));
    }

    @Auth(Constants.ROLE_ROOT_NAME)
    @GetMapping("/freeze/{id}")
    public RestResult freezeUser(@PathVariable("id")Integer id){

        User user = new User();
        user.setId(id);

        return new RestResult(userService.freezeUser(user));
    }

    @GetMapping("/allow/{loginId}")
    public RestResult<String> checkLoginId(@PathVariable("loginId")String loginId){

        if(!userService.checkLoginId(loginId)){
            return new RestResult<>("");
        }
        return new RestResult<>(ResultsEnum.SYS_ERROR);
    }

}
